package edu.zut.cs.software.practice;

import org.apache.activemq.ActiveMQConnectionFactory;

import java.sql.SQLException;

import javax.jms.*;

/**
 * 
 * @author 陈明阳
<<<<<<< HEAD
 * @author 马江涛
=======
 * @author 黄靖
>>>>>>> 05ca3405ac39cef5e837c5927862f04da93739e0
 *
 */
public class MessageConsumer {
	static student stu= new student();
	static studentManagerImpl sMI=new studentManagerImpl();
	
	
	// 定义ActivMQ的连接地址
	private static final String ACTIVEMQ_URL = "tcp://127.0.0.1:61616";
	// 定义发送消息的队列名称
	private static final String QUEUE_NAME = "MyMessage";

	public void MessageReceive() throws JMSException {
		// 创建连接工厂
		ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(ACTIVEMQ_URL);
		// 创建连接
		Connection connection = activeMQConnectionFactory.createConnection();

		// 打开连接
		connection.start();

		// 创建会话
		Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
		// 创建队列目标
		Destination destination = session.createQueue(QUEUE_NAME);
		// 创建消费者
		javax.jms.MessageConsumer consumer = session.createConsumer(destination);

		// 创建消费的监听
		consumer.setMessageListener(new MessageListener() {
			@Override
			public void onMessage(Message message) {
				TextMessage textMessage = (TextMessage) message;
				try {
					//控制台显示收到的信息
					System.out.println("Message Receiving：" + textMessage.getText());
					String tempString = textMessage.getText();
					String[] s = tempString.split("\\s+");// \\s表示 空格,回车,换行等空白符,+号表示一个或多个的意思
					
					stu.setId(s[0]);
					try {
						sMI.add(stu);//将带有信息的学生传入实现添加
					} catch (SQLException e) {
						e.printStackTrace();
					}
					
				} catch (JMSException e) {
					e.printStackTrace();
				}
				
				
				/*
				TextMessage textMessage = (TextMessage) message;
				try {
					System.out.println("获取消息：" + textMessage.getText());
				} catch (JMSException e) {
					e.printStackTrace();
				}
				*/
				
			}
		});
	}
}
